package thu.cs.segroup.parser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import thu.cs.segroup.rule.Assertion;
import thu.cs.segroup.rule.Rule;

public class RuleParser {

	public static Rule parseRules(File rule_file) {
		Document doc;
		SAXReader reader = new SAXReader();
		Rule rule = new Rule();
		
		try {
			doc = reader.read(rule_file);
			Element root = doc.getRootElement();
			Node event = root.selectSingleNode("event");
			if (event != null) {
				rule.setEvent(event.getStringValue());
			}
			
			List<Element> assertions = root.selectNodes("assertion");
			for (int i = 0; i < assertions.size(); i++) {
				Assertion assertion = new Assertion();
				assertion.setKey(assertions.get(i).attributeValue("prop_name"));
				assertion.setOp(assertions.get(i).attributeValue("operator"));
				assertion.setValue(assertions.get(i).attributeValue("prop_value"));
				rule.addAssertion(assertion);
			}
			
			Node action = root.selectSingleNode("action");
			if (action != null) {
				rule.setBehavName(action.getStringValue());
			}
			
			return rule;
			
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
}
